'use client';

import { useEffect, useState } from 'react';
import { Table, message, Button, Modal, Form, Input, Pagination, Spin } from 'antd';
import { useUser } from '../../context/userContext';
import api from '../../utils/api';
import styles from '@/components/Font.module.css';

export default function TagManagementPage() {
    const { user } = useUser();
    const accessToken = user?.access_token || "";

    // 分页状态
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(10); // 固定每页显示数量
    const [totalTags, setTotalTags] = useState(0);

    // 标签状态
    const [tags, setTags] = useState([]);
    const [createTagModalVisible, setCreateTagModalVisible] = useState(false);
    const [updateTagModalVisible, setUpdateTagModalVisible] = useState(false);
    const [selectedTag, setSelectedTag] = useState(null);
    const [loading, setLoading] = useState(false);

    // 表单实例
    const [createTagForm] = Form.useForm();
    const [updateTagForm] = Form.useForm();

    const fetchTags = async () => {
        setLoading(true);
        try {
            const response = await api.get('/tags/all', {
                headers: { Authorization: `Bearer ${accessToken}` },
                params: { page: currentPage, pageSize: pageSize }
            });

            if (!response.data || !Array.isArray(response.data.Tags)) {
                console.error('标签数据格式错误', response.data);
                throw new Error('标签数据获取失败');
            }

            setTags(response.data.Tags);
            setTotalTags(response.data.total || 0);
        } catch (error) {
            console.log('获取标签失败', error);
            message.error('标签加载失败');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchTags();
    }, [currentPage, pageSize, accessToken]);

    // 创建标签
    const handleCreateTag = async (values) => {
        try {
            const response = await api.post('/tags/create', values, {
                headers: { 
                    Authorization: `Bearer ${accessToken}`,
                    'Content-Type': 'application/json'
                }
            });

            if (response.status === 201) {
                message.success('标签创建成功');
                setCreateTagModalVisible(false);
                await fetchTags();
            }
        } catch (error) {
            console.log('创建标签失败', error);
            message.error('标签创建失败');
        }
    };

    // 更新标签
    const handleUpdateTag = async (values) => {
        if (!selectedTag?.id) return;

        try {
            const requestData = {
                id: selectedTag.id,
                ...values
            };

            const response = await api.put('/tags/update', requestData, {
                headers: { 
                    Authorization: `Bearer ${accessToken}`,
                    'Content-Type': 'application/json'
                }
            });

            if (response.status === 200) {
                message.success('标签更新成功');
                setUpdateTagModalVisible(false);
                await fetchTags();
            }
        } catch (error) {
            console.log('更新标签失败', error);
            message.error('标签更新失败');
        }
    };

    // 删除标签
    const handleDeleteTag = async (tagId) => {
        try {
            const response = await api.delete(`/tags/delete?id=${tagId}`, {
                headers: { Authorization: `Bearer ${accessToken}` }
            });

            if (response.status === 200) {
                message.success('标签删除成功');
                await fetchTags();
            }
        } catch (error) {
            console.log('删除标签失败', error);
            message.error('标签删除失败');
        }
    };

    // 表格列定义
    const tagColumns = [
        { 
            title: 'ID', 
            dataIndex: 'id', 
            key: 'id',
            className: styles.text,
            width: 80,
        },
        { 
            title: '名称', 
            dataIndex: 'name', 
            key: 'name',
            className: styles.text,
            width: 150,
        },
        { 
            title: '描述', 
            dataIndex: 'description', 
            key: 'description',
            className: styles.text,
            width: 300,
        },
        {
            title: '操作',
            key: 'action',
            className: styles.text,
            width: 220,
            render: (_, record) => (
                <div className="flex space-x-2">
                    <Button 
                        type="primary" 
                        className="bg-[#D6A7A1] hover:bg-[#E8D6D0] text-white rounded-md transition-all text-sm px-3 py-1.5"
                        onClick={() => {
                            setSelectedTag(record);
                            updateTagForm.setFieldsValue(record);
                            setUpdateTagModalVisible(true);
                        }}
                    >
                        更新
                    </Button>
                    <Button 
                        type="primary" 
                        danger 
                        className="bg-[#A3989D] hover:bg-[#C1B7B0] text-white rounded-md transition-all text-sm px-3 py-1.5"
                        onClick={() => handleDeleteTag(record.id)}
                    >
                        删除
                    </Button>
                </div>
            )
        }
    ];

    return (
        <div className="bg-[#F4EDEB] rounded-2xl shadow-md p-6">
            <h2 className={`${styles.titlesmall} text-xl mb-6 text-[#7A6E6E]`}>标签管理</h2>
            
            <Button 
                type="primary" 
                className="bg-[#D6A7A1] hover:bg-[#E8D6D0] text-white rounded-md transition-all text-sm px-4 py-2 mb-6"
                onClick={() => setCreateTagModalVisible(true)}
            >
                创建标签
            </Button>
            
            {/* 表格容器 - 固定表头，内容可滚动 */}
            <div className="overflow-hidden bg-white rounded-xl shadow-sm h-[calc(100vh-260px)]">
                <Spin spinning={loading}>
                    <Table
                        columns={tagColumns}
                        dataSource={tags}
                        pagination={false}
                        className="bordered={false}"
                        rowClassName={(record, index) => index % 2 === 0 ? 'bg-white' : 'bg-[#F4EDEB]/50'}
                        size="middle"
                        scroll={{ y: "calc(100vh - 260px)" }}
                        components={{
                            header: {
                                cell: ({ className, ...restProps }) => (
                                    <th
                                        {...restProps}
                                        className={`${className} ${styles.titlesmall} text-base font-semibold text-[#7A6E6E] bg-[#F4EDEB] sticky top-0 z-10`}
                                    />
                                ),
                            },
                        }}
                    />
                </Spin>
            </div>
            
            {/* 分页组件 - 移除每页显示数量选择器 */}
            <div className="flex justify-center mt-6">
                <Pagination
                    current={currentPage}
                    pageSize={pageSize}
                    total={totalTags}
                    onChange={newPage => setCurrentPage(newPage)}
                    className="bg-white p-3 rounded-lg shadow-sm"
                />
            </div>

            {/* 创建标签模态框 */}
            <Modal
                title={<span className={`${styles.titlesmall} text-base font-semibold text-[#7A6E6E]`}>创建标签</span>}
                visible={createTagModalVisible}
                onOk={() => createTagForm.submit()}
                onCancel={() => setCreateTagModalVisible(false)}
                className="rounded-xl overflow-hidden bg-[#F4EDEB]"
                style={{ borderRadius: '16px' }}
                footer={[
                    <Button 
                        key="cancel" 
                        className="bg-[#A3989D] hover:bg-[#C1B7B0] text-white rounded-md transition-all text-sm px-3 py-1.5"
                        onClick={() => setCreateTagModalVisible(false)}
                    >
                        取消
                    </Button>,
                    <Button 
                        key="ok" 
                        type="primary"
                        className="bg-[#D6A7A1] hover:bg-[#E8D6D0] text-white rounded-md transition-all text-sm px-3 py-1.5"
                        onClick={() => createTagForm.submit()}
                    >
                        创建
                    </Button>,
                ]}
            >
                <div className="p-4 bg-white rounded-lg shadow-sm">
                    <Form 
                        form={createTagForm} 
                        layout="vertical" 
                        onFinish={handleCreateTag}
                    >
                        <Form.Item
                            label={<span className={`${styles.text} font-medium text-gray-700`}>标签名称</span>}
                            name="name"
                            rules={[{ required: true, message: '请输入标签名称' }]}
                        >
                            <Input className="rounded-md border-gray-300 focus:border-[#D6A7A1] focus:ring focus:ring-[#D6A7A1]/20 transition-all" />
                        </Form.Item>
                        <Form.Item
                            label={<span className={`${styles.text} font-medium text-gray-700`}>标签描述</span>}
                            name="description"
                            rules={[{ message: '请输入标签描述' }]}
                        >
                            <Input className="rounded-md border-gray-300 focus:border-[#D6A7A1] focus:ring focus:ring-[#D6A7A1]/20 transition-all" />
                        </Form.Item>
                    </Form>
                </div>
            </Modal>

            {/* 更新标签模态框 */}
            <Modal
                title={<span className={`${styles.titlesmall} text-base font-semibold text-[#7A6E6E]`}>更新标签</span>}
                visible={updateTagModalVisible}
                onOk={() => updateTagForm.submit()}
                onCancel={() => setUpdateTagModalVisible(false)}
                className="rounded-xl overflow-hidden bg-[#F4EDEB]"
                style={{ borderRadius: '16px' }}
                footer={[
                    <Button 
                        key="cancel" 
                        className="bg-[#A3989D] hover:bg-[#C1B7B0] text-white rounded-md transition-all text-sm px-3 py-1.5"
                        onClick={() => setUpdateTagModalVisible(false)}
                    >
                        取消
                    </Button>,
                    <Button 
                        key="ok" 
                        type="primary"
                        className="bg-[#D6A7A1] hover:bg-[#E8D6D0] text-white rounded-md transition-all text-sm px-3 py-1.5"
                        onClick={() => updateTagForm.submit()}
                    >
                        更新
                    </Button>,
                ]}
            >
                <div className="p-4 bg-white rounded-lg shadow-sm">
                    <Form 
                        form={updateTagForm} 
                        layout="vertical" 
                        initialValues={selectedTag || {}}
                        onFinish={handleUpdateTag}
                    >
                        <Form.Item
                            label={<span className={`${styles.text} font-medium text-gray-700`}>标签ID</span>}
                            name="id"
                            disabled
                        >
                            <Input className="rounded-md border-gray-300 bg-gray-100 cursor-not-allowed" disabled />
                        </Form.Item>
                        <Form.Item
                            label={<span className={`${styles.text} font-medium text-gray-700`}>标签名称</span>}
                            name="name"
                            rules={[{ required: true, message: '请输入标签名称' }]}
                        >
                            <Input className="rounded-md border-gray-300 focus:border-[#D6A7A1] focus:ring focus:ring-[#D6A7A1]/20 transition-all" />
                        </Form.Item>
                        <Form.Item
                            label={<span className={`${styles.text} font-medium text-gray-700`}>标签描述</span>}
                            name="description"
                            rules={[{ message: '请输入标签描述' }]}
                        >
                            <Input className="rounded-md border-gray-300 focus:border-[#D6A7A1] focus:ring focus:ring-[#D6A7A1]/20 transition-all" />
                        </Form.Item>
                    </Form>
                </div>
            </Modal>
        </div>
    );
}